//
//  AppDelegate.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/10.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "AppDelegate.h"
#import "M1ShuntVC.h"
#import <AdSupport/AdSupport.h>
#import "M1CLLocationManage.h"
#import "IQKeyboardManager.h"
#import "AppDelegate+EaseMob.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "M1LoginJump.h"
#import "M1LaunchViewController.h"
//NSString * const m1_EaseMob_APPKey = @"maiyou2015#marryyou";
NSString * const m1_EaseMob_APPKey = @"marryyou#marryyou";
@interface AppDelegate ()<UNUserNotificationCenterDelegate>
@property (nonatomic ,strong) M1LaunchViewController *m1_launchVC;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    IQKeyboardManager *kbManager = [IQKeyboardManager sharedManager];
    kbManager.enable = YES;
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //self.window.rootViewController = [M1TabBarController new];
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    }
    [M1SaveTool m1_removeLocation];
    [[M1CLLocationManage shareInstance] m1_getLocation:nil faild:nil];
    WEAKSELF;
    _m1_launchVC = [M1LaunchViewController new];
    self.window.rootViewController = _m1_launchVC;
    _m1_launchVC.m1_reload = ^{
        [weakSelf m1_reloadConfig:application options:launchOptions];
    };
    
    [self m1_reloadConfig:application options:launchOptions];

    [M1User m1_removeImageCache];
    [self.window makeKeyAndVisible];
    
    return YES;
}
-(void)m1_reloadConfig:(UIApplication *)application options:(NSDictionary *)launchOptions{
    WEAKSELF;
    [self m1_updateConfig:^(BOOL isSuccess) {
        if (isSuccess) {
            [weakSelf m1_configurationEm:application didFinishLaunchingWithOptions:launchOptions];
            [weakSelf m1_registApns:application];
            [weakSelf m1_configUM];
            [weakSelf m1_configIfa];
            if ([M1User user]) {
                [weakSelf m1_tokenLogin];
                
            }else{
                M1ShuntVC *vc = [M1ShuntVC new];
                weakSelf.window.rootViewController = [[M1NavigationController alloc]initWithRootViewController:vc];
            }
        }else{
            [weakSelf.m1_launchVC m1_reloadConfig];
        }
    }];
}

-(void)m1_configIfa{
    [M1HttpNet requestWithMethod:@"app/device/device" params:@{@"ifa":[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]} success:^(id resDic, NSInteger code, NSString *message) {
        
    } fail:^(id resDic, NSInteger code, NSString *message) {
        
    } showAni:NO];
}
-(void)m1_configUM{
    [UMConfigure initWithAppkey:@"5518f935fd98c5df85000210" channel:@"AppStore_SK"];
    if ([M1User user]) {
        [MobClick profileSignInWithPUID:[M1User user].basic.uid];
    }
}
-(void)m1_tokenLogin{
    WEAKSELF;
    [M1HttpNet requestWithMethod:m1_token_login_url params:nil success:^(id resDic, NSInteger code, NSString *message) {
        [M1User save:resDic];
        [M1LoginJump m1_loginWith:[M1User user] vc:nil];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        M1ShuntVC *vc = [M1ShuntVC new];
        weakSelf.window.rootViewController = [[M1NavigationController alloc]initWithRootViewController:vc];
    } showAni:NO];
}

-(void)m1_updateConfig:(void(^)(BOOL isSuccess))block{
    NSString *we_chat = @"0";
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]]) {
        we_chat = @"1";
    }
    NSTimeZone *zone = [NSTimeZone localTimeZone];
    NSString *strZoneName = [zone name];
    NSDictionary *n1_params = @{@"ipad_value":[[UIDevice currentDevice] model],
                                @"time_zone":strZoneName,
                                @"we_chat":we_chat
                                };
    [M1HttpNet requestWithMethod:m1_system_stc_url params:n1_params success:^(id resDic, NSInteger code, NSString *message) {
        [M1SaveTool m1_saveAppConfig:resDic];
        block(YES);
    } fail:^(id resDic, NSInteger code, NSString *message) {
        block(NO);
    } showAni:NO];
}

-(void)m1_configurationEm:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [self easemobApplication:application
didFinishLaunchingWithOptions:launchOptions
                      appkey:m1_EaseMob_APPKey
                apnsCertName:@"DzhkDis"
                 otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
}
-(void)m1_registApns:(UIApplication *)application{
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType m1_notificationTypes = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound |
        UIUserNotificationTypeAlert;
        UIUserNotificationSettings *m1_settings = [UIUserNotificationSettings settingsForTypes:m1_notificationTypes categories:nil];
        [application registerUserNotificationSettings:m1_settings];
    }
    else{
        UIRemoteNotificationType m1_notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:m1_notificationTypes];
    }
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSDictionary *m1_userInfo = notification.request.content.userInfo;
    [self easemobApplication:[UIApplication sharedApplication] didReceiveRemoteNotification:m1_userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [self easemobApplication:application didReceiveRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient] bindDeviceToken:deviceToken];
    });
}


@end
